package org.sample.junit5.ex6;

import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;

public class ExecutionTimingExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {

    private static final String KEY = "start";

    @Override
    public void beforeTestExecution(ExtensionContext context) {
        context.getStore(ExtensionContext.Namespace.create(getClass(), context.getUniqueId()))
                .put(KEY, System.nanoTime());
    }

    @Override
    public void afterTestExecution(ExtensionContext context) {
        var store = context.getStore(ExtensionContext.Namespace.create(getClass(), context.getUniqueId()));
        Long start = store.remove(KEY, Long.class);
        if (start != null) {
            long ms = (System.nanoTime() - start) / 1_000_000;
            context.publishReportEntry("test", context.getDisplayName());
            context.publishReportEntry("durationMs", String.valueOf(ms));
        }
    }
}
